import Vue from 'vue'
import VueRouter from 'vue-router'
// import Home from '../views/Home.vue'
import Login from '../components/login.vue'
import Home from '../components/home.vue'
import Welcome from '../components/welcome.vue'
import Users from '../components/users.vue'
import Rights from '../components/rights.vue'
import Roles from '../components/roles.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    redirect: '/welcome',
    component: Home,
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫beforeEach
// 当用户没有登陆，但是直接通过url访问特定页面，需要重新导航到登录页面

router.beforeEach((to, from, next) => {
  // to将要访问的页面路径  from从哪个页面跳转过来的 next放行的函数
  // 如果用户直接访问登录页，直接放行
  if (to.path === '/login') {
    return next()
  }
  // 从sessionStorage中获取保存的token值，
  const tokenStr = window.sessionStorage.getItem('token')
  // 如果没有获取到token值，就强制跳转到登录页
  if (!tokenStr) {
    return next('/login')
  }
  next()
})

export default router
